
import { Input } from '@/components/ui/input';
import MenuToggle from '../components/MenuToggle';
import { Badge } from '@/components/ui/badge';
import { CardContent, CardHeader, Card, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Eye, Copy, Book, Search, ChevronDown, FileText, Code, Download, ExternalLink, ChevronRight } from 'lucide-react';
import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
const ApiDocs = ({ toggleSidebar }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('user-management');
  const [expandedSections, setExpandedSections] = useState(['overview']);

  // 文档分类
  const categories = [
    { id: 'user-management', name: '用户管理', count: 8 },
    { id: 'file-management', name: '文件管理', count: 12 },
    { id: 'auth', name: '认证授权', count: 6 },
    { id: 'system', name: '系统管理', count: 10 },
    { id: 'webhook', name: 'Webhook', count: 4 }
  ];

  // API文档数据
  const apiDocs = {
    'user-management': [
      {
        id: 'get-user',
        name: '获取用户信息',
        method: 'GET',
        path: '/api/v1/users/{id}',
        description: '根据用户ID获取用户详细信息',
        parameters: [
          { name: 'id', type: 'string', required: true, description: '用户ID' }
        ],
        responses: {
          200: {
            description: '成功返回用户信息',
            example: {
              id: '12345',
              name: '张三',
              email: 'zhangsan@example.com',
              status: 'active'
            }
          },
          404: {
            description: '用户不存在',
            example: {
              error: 'User not found',
              code: 404
            }
          }
        }
      },
      {
        id: 'create-user',
        name: '创建用户',
        method: 'POST',
        path: '/api/v1/users',
        description: '创建新用户账户',
        parameters: [
          { name: 'name', type: 'string', required: true, description: '用户姓名' },
          { name: 'email', type: 'string', required: true, description: '邮箱地址' },
          { name: 'password', type: 'string', required: true, description: '密码' }
        ],
        responses: {
          201: {
            description: '用户创建成功',
            example: {
              id: '12345',
              name: '张三',
              email: 'zhangsan@example.com',
              status: 'active'
            }
          },
          400: {
            description: '请求参数错误',
            example: {
              error: 'Invalid parameters',
              code: 400
            }
          }
        }
      }
    ]
  };

  const toggleSection = (sectionId) => {
    setExpandedSections(prev => 
      prev.includes(sectionId) 
        ? prev.filter(id => id !== sectionId)
        : [...prev, sectionId]
    );
  };

  const copyToClipboard = (text) => {
    navigator.clipboard.writeText(text);
    // 这里可以添加复制成功的提示
  };

  const getMethodBadge = (method) => {
    const methodConfig = {
      GET: { color: 'bg-blue-100 text-blue-800' },
      POST: { color: 'bg-green-100 text-green-800' },
      PUT: { color: 'bg-orange-100 text-orange-800' },
      DELETE: { color: 'bg-red-100 text-red-800' }
    };
    
    const config = methodConfig[method] || methodConfig.GET;
    return (
      <Badge className={`${config.color} hover:${config.color} font-mono text-xs`}>
        {method}
      </Badge>
    );
  };

  const currentDocs = apiDocs[selectedCategory] || [];

  return (
    <>
      {/* 头部工具栏 */}
      <div className="mt-3">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-green-500 to-green-600 rounded-xl flex items-center justify-center">
                  <FileText className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    接口文档
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    API接口详细文档和使用说明
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-material-grey-500" />
                <input
                  type="text"
                  placeholder="搜索接口文档..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10 pr-4 py-2 w-80 border border-material-grey-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors"
                />
              </div>

              <Button variant="outline">
                <Download className="w-4 h-4 mr-2" />
                导出文档
              </Button>

              <Button variant="outline">
                <ExternalLink className="w-4 h-4 mr-2" />
                在线调试
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          {/* 左侧：文档导航 */}
          <div className="lg:col-span-1">
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">文档分类</CardTitle>
              </CardHeader>
              <CardContent className="p-0">
                <div className="space-y-1">
                  {categories.map((category) => (
                    <button
                      key={category.id}
                      onClick={() => setSelectedCategory(category.id)}
                      className={`w-full flex items-center justify-between px-4 py-3 text-left hover:bg-material-grey-50 transition-colors ${
                        selectedCategory === category.id 
                          ? 'bg-primary/10 text-primary border-r-2 border-primary' 
                          : 'text-material-grey-700'
                      }`}
                    >
                      <div className="flex items-center space-x-3">
                        <Book className="w-4 h-4" />
                        <span className="font-medium">{category.name}</span>
                      </div>
                      <Badge variant="secondary" className="text-xs">
                        {category.count}
                      </Badge>
                    </button>
                  ))}
                </div>
              </CardContent>
            </Card>

            {/* 快速链接 */}
            <Card className="mt-6">
              <CardHeader>
                <CardTitle className="text-lg">快速链接</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <Button variant="outline" className="w-full justify-start">
                  <Code className="w-4 h-4 mr-2" />
                  SDK下载
                </Button>
                <Button variant="outline" className="w-full justify-start">
                  <FileText className="w-4 h-4 mr-2" />
                  Postman集合
                </Button>
                <Button variant="outline" className="w-full justify-start">
                  <ExternalLink className="w-4 h-4 mr-2" />
                  在线测试
                </Button>
              </CardContent>
            </Card>
          </div>

          {/* 右侧：文档内容 */}
          <div className="lg:col-span-3">
            {/* 概览信息 */}
            <Card className="mb-6">
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Book className="w-5 h-5" />
                  <span>API概览</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="text-center p-4 bg-blue-50 rounded-lg">
                    <div className="text-2xl font-bold text-blue-600">40+</div>
                    <div className="text-sm text-blue-800">API接口</div>
                  </div>
                  <div className="text-center p-4 bg-green-50 rounded-lg">
                    <div className="text-2xl font-bold text-green-600">v1.2</div>
                    <div className="text-sm text-green-800">当前版本</div>
                  </div>
                  <div className="text-center p-4 bg-purple-50 rounded-lg">
                    <div className="text-2xl font-bold text-purple-600">99.9%</div>
                    <div className="text-sm text-purple-800">可用性</div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* API文档列表 */}
            <div className="space-y-4">
              {currentDocs.map((api) => (
                <Card key={api.id}>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-3">
                        {getMethodBadge(api.method)}
                        <div>
                          <h3 className="text-lg font-semibold text-material-grey-900">{api.name}</h3>
                          <code className="text-sm text-material-grey-600 bg-material-grey-100 px-2 py-1 rounded">
                            {api.path}
                          </code>
                        </div>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => copyToClipboard(api.path)}
                        >
                          <Copy className="w-4 h-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => toggleSection(api.id)}
                        >
                          {expandedSections.includes(api.id) ? (
                            <ChevronDown className="w-4 h-4" />
                          ) : (
                            <ChevronRight className="w-4 h-4" />
                          )}
                        </Button>
                      </div>
                    </div>
                    <p className="text-material-grey-600">{api.description}</p>
                  </CardHeader>

                  {expandedSections.includes(api.id) && (
                    <CardContent>
                      <Tabs defaultValue="parameters" className="w-full">
                        <TabsList className="grid w-full grid-cols-3">
                          <TabsTrigger value="parameters">参数</TabsTrigger>
                          <TabsTrigger value="responses">响应</TabsTrigger>
                          <TabsTrigger value="examples">示例</TabsTrigger>
                        </TabsList>

                        <TabsContent value="parameters" className="mt-4">
                          <div className="space-y-3">
                            <h4 className="font-medium text-material-grey-900">请求参数</h4>
                            <div className="overflow-x-auto">
                              <table className="w-full text-sm">
                                <thead>
                                  <tr className="border-b border-material-grey-200">
                                    <th className="text-left py-2 px-3">参数名</th>
                                    <th className="text-left py-2 px-3">类型</th>
                                    <th className="text-left py-2 px-3">必填</th>
                                    <th className="text-left py-2 px-3">说明</th>
                                  </tr>
                                </thead>
                                <tbody>
                                  {api.parameters.map((param, index) => (
                                    <tr key={index} className="border-b border-material-grey-100">
                                      <td className="py-2 px-3 font-mono text-blue-600">{param.name}</td>
                                      <td className="py-2 px-3 text-material-grey-600">{param.type}</td>
                                      <td className="py-2 px-3">
                                        {param.required ? (
                                          <Badge className="bg-red-100 text-red-800">必填</Badge>
                                        ) : (
                                          <Badge variant="secondary">可选</Badge>
                                        )}
                                      </td>
                                      <td className="py-2 px-3 text-material-grey-600">{param.description}</td>
                                    </tr>
                                  ))}
                                </tbody>
                              </table>
                            </div>
                          </div>
                        </TabsContent>

                        <TabsContent value="responses" className="mt-4">
                          <div className="space-y-4">
                            <h4 className="font-medium text-material-grey-900">响应说明</h4>
                            {Object.entries(api.responses).map(([code, response]) => (
                              <div key={code} className="border border-material-grey-200 rounded-lg p-4">
                                <div className="flex items-center space-x-2 mb-2">
                                  <Badge className={code === '200' || code === '201' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}>
                                    {code}
                                  </Badge>
                                  <span className="text-sm text-material-grey-700">{response.description}</span>
                                </div>
                                <pre className="bg-material-grey-50 p-3 rounded text-sm overflow-x-auto">
                                  <code>{JSON.stringify(response.example, null, 2)}</code>
                                </pre>
                              </div>
                            ))}
                          </div>
                        </TabsContent>

                        <TabsContent value="examples" className="mt-4">
                          <div className="space-y-4">
                            <h4 className="font-medium text-material-grey-900">请求示例</h4>
                            <div className="bg-material-grey-900 text-white p-4 rounded-lg">
                              <div className="flex items-center justify-between mb-2">
                                <span className="text-sm text-material-grey-300">cURL</span>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="text-white hover:bg-white/10"
                                  onClick={() => copyToClipboard(`curl -X ${api.method} "${api.path}"`)}
                                >
                                  <Copy className="w-4 h-4" />
                                </Button>
                              </div>
                              <pre className="text-sm">
                                <code>{`curl -X ${api.method} "${api.path}" \\
  -H "Content-Type: application/json" \\
  -H "Authorization: Bearer YOUR_TOKEN"`}</code>
                              </pre>
                            </div>
                          </div>
                        </TabsContent>
                      </Tabs>
                    </CardContent>
                  )}
                </Card>
              ))}
            </div>

            {/* 空状态 */}
            {currentDocs.length === 0 && (
              <div className="text-center py-12">
                <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
                  <FileText className="w-8 h-8 text-material-grey-500" />
                </div>
                <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                  暂无文档
                </h3>
                <p className="text-material-grey-500">
                  该分类下暂时没有API文档
                </p>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default ApiDocs;
